<?php

namespace App\Model;

use Hyperf\Utils\Arr;

/**
 * App\Coupon
 *
 * @property int $id
 * @property int $distributor_id
 * @property string $type 优惠卷类型
 * @property float $fee 抵扣金额
 * @property int $days 有效天数
 * @property int $quantity 发卷数量
 * @property-read int|null $devices_count
 * @property-read int|null $records_count
 */
class Coupon extends Model
{
    public bool $timestamps = true;
    protected ?string $table = 'coupons';

    const COUPON_DEVICE_CACHE = 'coupon_device_cache';
    const COUPON_MONEY_CACHE = 'coupon_money_cache';
    const DEFAULT_FEE = 1;

    const TYPE_NEW_USER = 'new_user';
    const TYPE_RECHARGE_RECEIVE = 'recharge_receive';

    const TYPE_MAP = [
        self::TYPE_NEW_USER => '1元现金充电券',
        self::TYPE_RECHARGE_RECEIVE => '充值赠送充电券',
    ];

    protected array $casts = [
    ];


    protected array $fillable = [
       'is_active', 'type', 'start_date', 'end_date', 'fee', 'days', 'quantity','content','images','distributor_id'
    ];

    public function scopeNewUser($query)
    {
        return $query->where('type', self::TYPE_NEW_USER);
    }

    public function records()
    {
        return $this->hasMany(CouponRecord::class,'coupon_id','id');
    }

    public function usedRecords()
    {
        return $this->records()->whereNotNull('used_at');
    }

    public function devices()
    {
        return $this->belongsToMany(Device::class, 'coupon_devices');
    }

    public function distributor()
    {
        return $this->belongsTo(Distributors::class,'id','distributor_id');
    }

    public function scopeEffective($query)
    {
        return $query->where('start_date', '<', now())->where('end_date', '>', now());
    }

    public function getTypeDescAttribute()
    {
        return Arr::get(static::TYPE_MAP, $this->type);
    }


    public function checkCanReceive(User $user)
    {

        return $this->records_count < $this->quantity;
//        switch ($this->type)
//        {
//            case self::TYPE_NEW_USER:
//                //今天注册的才可以
//                return $user->created_at->isSameDay(now());
//        }
//
//
//        return false;
    }


}
